package hxy.dragon.rpc;

import hxy.dragon.rpc.impl.HelloServiceImpl;

import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.rmi.RemoteException;

public class RpcServer {
    public static void main(String[] args) {
        try {
            ServerSocket serverSocket = new ServerSocket(8888);
            System.out.println("RPC Server is running and waiting for client...");

            while (true) {
                Socket clientSocket = serverSocket.accept();
                System.out.println("Client connected: " + clientSocket);

                // 读取客户端的请求
                ObjectInputStream ois = new ObjectInputStream(clientSocket.getInputStream());
                String methodName = (String) ois.readObject();
                Object[] params = (Object[]) ois.readObject();

                // 调用服务
                Object result = invokeService(methodName, params);

                // 返回结果给客户端
                ObjectOutputStream oos = new ObjectOutputStream(clientSocket.getOutputStream());
                oos.writeObject(result);

                ois.close();
                oos.close();
                clientSocket.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 根据方法名调用对应的服务方法
    private static Object invokeService(String methodName, Object[] params) throws RemoteException {
        if (methodName.equals("hello")) {
            String name = (String) params[0];
            // 创建并调用服务实现类
            HelloService service = new HelloServiceImpl();
            try {
                return service.hello(name);
            } catch (RemoteException e) {
                e.printStackTrace();
                return null;
            }
        } else {
            return null; // 可以根据需要扩展其他方法
        }
    }
}
